package com.example.webapi.Utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
import com.example.webapi.entity.Listdata;
import com.example.webapi.service.ListdataService;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WriteJson {
    /**
     * 封装写入json数据
     */
    public static void wrtie(ListdataService listdataService) {
        // 进阶json路径
        Setting setting = new Setting("config/project.setting");
        String exePath = setting.getStr("exePath");
        File exeFile = FileUtil.file(exePath);
        String ParentPath = exeFile.getParent();
        String savePath = ParentPath + File.separator + "CheckStand.Json";
        //拼接数据
        Map<String, Map<String, Object>> map = new HashMap<>();
        Map<String, Object> type1 = new HashMap<>();
        Map<String, Object> type2 = new HashMap<>();
        Map<String, Object> type3 = new HashMap<>();
        Map<String, Object> type4 = new HashMap<>();
        List<Listdata> listdata = listdataService.list();
        for (Listdata dbData : listdata) {
            if (dbData.getTypeID() == 1) {
                type1.put(dbData.getBuildingHeight(), dbData.getBuildingWidth());
            }
            if (dbData.getTypeID() == 2) {
                type2.put("面积", dbData.getLandArea());
            }
            if (dbData.getTypeID() == 3) {
//                wrapper.select("id","facilityName","controlValue","serveScale","areaType");
                type3.put(dbData.getFacilityName(), dbData.getControlValue());
            }
            if (dbData.getTypeID() == 4) {
                type4.put(Convert.toStr(dbData.getId()), dbData.getRatio());
            }
        }
        map.put("面宽检测", type1);
        map.put("绿地面积检测", type2);
        map.put("配套设施检测", type3);
        map.put("车位复核检测", type4);
        //写入文件
        try {
            File file = FileUtil.file(savePath);
//            file.mkdir(file.getParent());
            if (!file.exists()) {
                FileUtil.mkParentDirs(file); //创建所给文件或目录的父目录
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(savePath));
            out.write(JSONUtil.toJsonStr(map));
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
